package com.xl333.mysql;

import com.xl333.mysql.model.Table;
import com.xl333.mysql.service.TableService;
import com.xl333.thymeleaf.ThymeleafUtil;
import com.xl333.util.FileUtil;
import com.xl333.util.PropertiesUtil;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.util.StringUtils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * @author 七月的狮子
 * @date 2020/5/25
 */
public class Creator {

    private static Creator instance = null;

    private String packageName = PropertiesUtil.getValue("java.packageName");

    private String filePath = packageName.replace('.', File.separatorChar) + File.separatorChar;

    private Creator(){

    }

    public static Creator getInstance(){
        if(instance == null){
            instance = new Creator();
        }
        return instance;
    }

    public void create(){
        String [] tableNames = null;
        String tableName = PropertiesUtil.getValue("database.table");
        if(!StringUtils.isEmpty(tableName)){
            tableNames = tableName.split(",");
        }

        List<Table> tableList = TableService.getInstance().getTableInfo(
                PropertiesUtil.getValue("database.name"), tableNames);
        TemplateEngine templateEngine = ThymeleafUtil.getInstance().getTemplateEngine();
        Context context = new Context(Locale.CHINA);
        for(Table table:tableList){
            Map<String, Object> param = new HashMap<>();
            param.put("table", table);
            param.put("packageName", packageName);
            context.setVariables(param);
            createModel(templateEngine, context, table);
            createMapper(templateEngine, context, table);
            createSqlmap(templateEngine, context, table);
        }
        System.out.println("自动生成工具执行完毕！");
    }

    private void createModel(TemplateEngine templateEngine, Context context, Table table){
        FileUtil.createFile(filePath + table.getSecondHumpName() + File.separatorChar + "model" + File.separatorChar,
                table.getHumpName() + ".java",
                templateEngine.process("/model.txt", context));
    }

    private void createMapper(TemplateEngine templateEngine, Context context, Table table){
        FileUtil.createFile(filePath + table.getSecondHumpName() + File.separatorChar + "mapper" + File.separatorChar,
                table.getHumpName() + "Mapper.java",
                templateEngine.process("/mapper.txt", context));
    }

    private void createSqlmap(TemplateEngine templateEngine, Context context, Table table){
        FileUtil.createFile(filePath + table.getSecondHumpName() + File.separatorChar + "mapper" + File.separatorChar,
                table.getSecondHumpName() + ".xml",
                templateEngine.process("/sqlmap.txt", context));
    }

}
